package com.wangjiang.service.shiro;

import com.wangjiang.model.UserModel;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShiroService {
    public static List<UserModel> userList = new ArrayList<UserModel>();

    public String getPasswordByUsername(String username){
        switch (username){
            case "liming":
                return "123";
            case "hanli":
                return "456";
            default:
                return null;
        }
    }

    //根据用户名查询用户
    public UserModel getUserByUsername(String username) {
        System.out.println("登陆的用户 " + username);
        for (UserModel user : userList) {
            if (username.equals(user.getUser_name())) {
                return user;
            }
        }
        return null;
    }

    //添加用户
    public UserModel addUser(String username, String password) {
//        //通过MD5的方式加密密码
//        String newpwd = new SimpleHash("MD5", password).toHex();
        // MD5 加盐
//        String newpwd = new SimpleHash("MD5", password, ByteSource.Util.bytes(username)).toHex();
        // MD5 encodeByBCrypt
        String newpwd = encodeByBCrypt(password);

        UserModel user = new UserModel();
        user.setUser_name(username);
        user.setPassword(newpwd);

        userList.add(user);

        System.out.println(user);
        return user;
    }

    public String encodeByMD5(String password) {
        return new SimpleHash("MD5", password).toHex();
    }

    public String encodeByMD5AndSalt(String password, String salt) {
        return new SimpleHash("MD5", password, ByteSource.Util.bytes(salt)).toHex();
    }

    public String encodeByBCrypt(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }
}
